/**
 * TmFileController
 *
 * @description :: Server-side logic for managing Tmfiles
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var qiniu = require('qiniu');
var rndstr = require("randomstring");

module.exports = {

	upload : function(req, res) {
		
		//console.log(sails.getBaseUrl());
		//var fieldname = req.param("fieldname");
		req.file('file').upload({},function (err, uploadedFiles) {
			if (err) {
				sails.log.error(err);
				return res.negotiate(err);
			}
			if (uploadedFiles.length === 0){
				return res.badRequest('No file was uploaded');
			}
			var putPolicy = new qiniu.rs.PutPolicy(sails.config.qiniu.bucket);
			var token = putPolicy.token();
			var extra = new qiniu.io.PutExtra();
			var filename = rndstr.generate(20);
				
			qiniu.io.putFile(token, filename, uploadedFiles[0].fd , extra, function(err, ret) {
				if (!err) {
					return res.send({
						success : true,
						filename : sails.config.qiniu.baseUrl + '/' + filename
					});
				} else {
					sails.log.error(err);
					return res.send({
						success : false,
						ret : err
					});
				}
			});
		});
	},
};
